<?php
/**
 * fba发货操作
 * User: bgl
 * Date: 2022/7/27 11:24
 * IDE： PhpStorm
 */

namespace App\Admin\Controllers\CustomerDelivery;

use App\Admin\Ajax\CustomerDelivery\DeliveryFbaAjax;
use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlat;
use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\SalesReport\FBAInventory;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class DeliveryFbaController extends AdminController
{

    protected $title = 'FBA发货';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'order_no' => null,
        'area_id' => null,
        'status' => null,
        'account_id' => null,
        'plat_id' => null,
        'sync_status' => null,
        'sku' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['order_no'] = $this->filters['order_no'];
        $filtersBlade['area_id'] = getOptions(SysArea::options(), $this->filters['area_id']);
        $filtersBlade['status'] = getOptions(CustomerDeliveryDetail::$_fbaStatusOption, $this->filters['status']);
        $filtersBlade['account_id'] = getOptions(SysPlatAccount::options(), $this->filters['account_id']);
        $filtersBlade['plat_id'] = getOptions(SysPlat::options(), $this->filters['plat_id']);
        $filtersBlade['sync_status'] = getOptions(CustomerDeliveryDetail::$_syncStatus, $this->filters['sync_status']);
        $filtersBlade['sku'] = $this->filters['sku'];

        return view('customer-delivery.delivery-fba.index', compact('paginator','action','filtersBlade'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = CustomerDelivery::query()
            ->where('delivery_type', CustomerDelivery::DELIVERY_TYPE_FBA) //发货方式 (1:FBA)
            ->where('status', '>=', CustomerDelivery::STATUS_DELIVERY_NO) //订单状态 (1:待备货 2:已备货 3:待发货 4:部分发货 5:已发货)
            ->orderBy('id', 'DESC');

        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'start_date'){
                $query->where('order_at','>=',$filter.' 00:00:00');
            }
            if($field == 'end_date'){
                $query->where('order_at','<=',$filter.' 23:59:59');
            }
            if($field == 'plat_id'){
                $query->where('plat_id',$filter);
            }
            if($field == 'account_id'){
                $query->whereHas('detail', function ($query) use($filter){
                    $query->where('account_id',$filter);
                });
            }
            if($field == 'status'){
                $query->whereHas('detail', function ($query) use($filter){
                    $query->where('status',$filter);
                });
            }
            if($field == 'sku'){
                $query->whereHas('detail.sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'sync_status'){
                $query->whereHas('detail', function ($query) use($filter){
                    $query->where('sync_status',$filter);
                });
            }
            if($field == 'order_no'){
                $query->where(function ($query) use($filter){
                    $query->where('delivery_no', 'like', "%{$filter}%")
                        ->orWhere('order_no', 'like', "%{$filter}%");
                });
            }
            if(in_array($field,['order_no', 'area_id', 'plat_id'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');

        $ajax = new DeliveryFbaAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');

        $modal = new DeliveryFbaAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }
    /**
     * 更换发货账号
     * @param int $detailId
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function update($detailId){

        $name = Request::get('name');
        $value = Request::get('value');
        $deliveryDetailsObj = CustomerDeliveryDetail::query()->where('id',$detailId)->first();
        if (!$deliveryDetailsObj){
            return response()->json(['status' => false, 'message' => '数据异常!']);
        }
        if('account_id' == $name){
            list($account_id,$seller_sku) = explode('_',$value);
            $deliveryDetailsObj->account_id = $account_id;
            $deliveryDetailsObj->seller_sku = $seller_sku;
        }else{
            $deliveryDetailsObj->{$name} = $value;
        }
        if(!$deliveryDetailsObj->save()){
            return response()->json(['status' => false, 'message' => '更换失败']);
        }else{
            return response()->json(['status' => true, 'message' => '更换成功']);
        }
    }

    /**
     * 下载FBA发货单据
     * @return \Illuminate\Http\JsonResponse
     */
    public function download(){
        try{

            $request = request();
            if (empty($request->get('ids'))) return response()->json(['status' => false, 'message' => '参数异常!']);

            $ids = $request->get('ids');
            $idArr = explode(',', $ids);

            $head = ['发货国家','原订单号','实际订单号','发货账号','收货国家','库存','SKU','品名','MerchantFulfillmentOrderID','DisplayableOrderID',
                'DisplayableOrderDate','MerchantSKU','Quantity','MerchantFulfillmentOrderItemID',
                'GiftMessage','DisplayableComment','PerUnitDeclaredValue','DisplayableOrderComment','DeliverySLA',
                'AddressName','AddressFieldOne','AddressFieldTwo','AddressFieldThree','AddressCity','AddressCountryCode','AddressStateOrRegion',
                'AddressPostalCode','AddressPhoneNumber','NotificationEmail'];

            $res = [];
            foreach ($idArr as $detailId) {
                //发货明细
                $deliveryDetailsObj = CustomerDeliveryDetail::query()->find($detailId);
                if(!in_array($deliveryDetailsObj->id, $idArr))continue;

                //发货单
                $deliveryObj = CustomerDelivery::query()->where('delivery_no', $deliveryDetailsObj->delivery_no)->first();
                if(empty($deliveryObj))continue;

                $orderNo = trim($deliveryObj->order_no);
                if(empty($orderNo))continue;

                $temp = [];
                $temp['country_id'] = $deliveryObj->country_id ? SysCountry::getCountryById($deliveryObj->country_id) : '未知'; //发货国家ID
                $temp['r_order_no'] = $deliveryObj->order_no ?? '';  //原订单号
                $temp['delivery_order_no'] = $deliveryDetailsObj->delivery_order_no ?? '';  //实际发货订单号
                $temp['account_id'] = $deliveryDetailsObj->account_id ? SysPlatAccount::getAccountById($deliveryDetailsObj->account_id) : '无可发账号'; //发货账号
                $temp['address_country'] = $deliveryObj->receiver->country ?? '未知'; //收货国家
                $temp['inventory'] = FBAInventory::getACccountFbaInventory($deliveryDetailsObj->account_id, $deliveryObj->area_id, $deliveryDetailsObj->psku_id); //库存

                $temp['psku_code'] = $deliveryDetailsObj->sku->psku_code ?? ''; //产品SKU编码
                $temp['psku_cn'] = $deliveryDetailsObj->sku->psku_cn ?? ''; //产品名称(中文)

                $temp['merchant_fulfillment_order_id'] = $orderNo; //品名
                $temp['displayable_order_id'] = $orderNo; //展示订单id
                $temp['displayable_order_date'] = date('c',strtotime($deliveryObj->order_at)) ?? ''; //展示订单时间
                $temp['merchant_sku'] = FBAInventory::getAreaSellerSku($deliveryDetailsObj->account_id, $deliveryObj->area_id, $deliveryDetailsObj->psku_id); //平台sku
                $temp['quantity'] = $deliveryDetailsObj->apply_num ?? 0; //订单数量
                $temp['merchant_fulfillment_order_item_id'] = $orderNo.'-'.$deliveryDetailsObj->id ?? ''; //全平台订单id
                $temp['gift_message'] = ''; //附加消息
                $temp['displayable_comment'] = ''; //展示回执信息
                $temp['per_unit_declared_value'] = '';  //公开单位值
                $temp['displayable_order_comment'] = 'Thank you for your order!'; //订单回执信息
                $temp['delivery_sla'] = 'Standard';  //状态

                $temp['address_name'] = $deliveryObj->receiver->receiver ?? '';  //收货人
                $temp['address_field_one'] = $deliveryObj->receiver->address ?? '';  //收货地址
                $temp['address_field_two'] = '';  //收货地址2
                $temp['address_field_three'] = '';  //收货地址3
                $temp['address_city'] = $deliveryObj->receiver->city ?? '';  //城市
                $temp['address_country_code'] = $deliveryObj->order->country_code ?? '';  //国家编码
                $temp['address_state_or_region'] = $deliveryObj->receiver->state ?? '';  //州
                $temp['address_postal_code'] = isset($deliveryObj->receiver->postcode) ? (substr($deliveryObj->receiver->postcode, 0, 1) == '0' ? "'".$deliveryObj->receiver->postcode : $deliveryObj->receiver->postcode) : ''; //邮编
                $temp['address_phone_number'] = $deliveryObj->receiver->phone ?? '';  //电话
                $temp['notification_email'] = '';  //邮箱
                $res[] = $temp;
            }
            if (empty($res)) return response()->json(['status' => false, 'message' => '暂无数据!']);

            set_time_limit(0);
            $response = new StreamedResponse(null, 200, [
                'Content-Type'        => 'text/csv;charset=utf-8',
                'Content-Disposition' => 'attachment;filename="FBA发货确认单.csv"',
            ]);
            $response->setCallback(function () use ($head, $res) {
                $fp = fopen('php://output', 'w');
                fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
                fputcsv($fp, $head);
                foreach ($res as $item) {
                    fputcsv($fp, $item);
                }
                fclose($fp);
            });
            $response->send();
            exit(0);
        }catch(\Exception $e){
            report($e);
        }
    }

}
